package com.clickpaas.timelineofUN.utils;

import com.alibaba.fastjson.JSONObject;
import com.clickpaas.timelineofUN.config.AutoLoadConfig;
import com.clickpaas.timelineofUN.constant.ConfConstant;
import com.clickpaas.timelineofUN.constant.ProjectConstant;
import com.clickpaas.timelineofUN.entity.ParamEntity.RetParamEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Slf4j
public class DataInfoUtil {

    /**
     * 通过token获取用户注册表ID
     * @return
     */
    public static String getSysUserIdByHttp(String token){
        if (StringUtils.isBlank(token)) return null;
        String info = getUserInfoByToken(token);

        if (StringUtils.isBlank(info)) return null;
        String userId = getUserIdByHttpStr(info);

        return userId;
    }

    /**
     * 根据token请求【AutoLoadConfig.URL】，获取用户登陆信息
     * @param token
     * @return
     */
    private static String getUserInfoByToken(String token){
        if(StringUtils.isBlank(token))return null;

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = null;
        try {
            // 通过址默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(AutoLoadConfig.URL);
            // 设置请求头信息，鉴权
            httpGet.setHeader("Authorization", "Bearer=da3efcbf-0845-4fe3-8aba-ee040be542c0");
            httpGet.setHeader("Cookie", "tokenId="+token);
            // 设置配置请求参数
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 请求超时时间
                    .setSocketTimeout(60000)// 数据读取超时时间
                    .build();
            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            log.info("GetUserInfo ERROR：【{}】",e.getMessage());
        } catch (IOException e) {
            log.info("GetUserInfo ERROR：【{}】",e.getMessage());
        } finally {
            // 关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.info("IO关闭异常：【{}】",e.getMessage());
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.info("IO关闭异常：【{}】",e.getMessage());
                }
            }
        }
        return result;
    }

    /**
     * 从登陆信息中获取用户ID
     * @param httpResult
     * @return
     */
    private static String getUserIdByHttpStr(String httpResult){
        //log.info("当前传入的HTTP入参是：【{}】",httpResult);
        if(null == httpResult){
            log.info("当前传入的HTTP入参是：【{}】",httpResult);
            return null;
        }
        JSONObject jsonObject = JsonUtil.jsonStrToJson(httpResult);
        if (null == jsonObject
                || StringUtils.isBlank(jsonObject.getString("code"))
                || !"200".equals(jsonObject.getString("code"))
                || StringUtils.isBlank(jsonObject.getString("data")))
            return null;

        String data = jsonObject.getString("data");
        JSONObject jsonData = JsonUtil.jsonStrToJson(data);
        if(null == jsonData
                || StringUtils.isBlank(jsonData.getString("userId")))
            return null;

        String userId = jsonData.getString("userId");
        if (StringUtils.isBlank(userId))
            return null;
        return userId;
    }

    /**
     * 判空转换为默认值
     * @param value 目标值
     * @param defaltValue 默认值
     * @return
     */
    public static String setDefaltValue(String value,String defaltValue){
        if(StringUtils.isBlank(value)){
            return defaltValue;
        }
        return value;
    }

    /**
     * 对动态更新特殊处理:
     * 融资轮次是个单选列表字段，有个选项是其他。如果值是其他，需要取 融资轮次_其他
     * 技术应用领域是个多选列表字段，有个选项是其他。如果值是其他，需要取 技术应用领域_其他 的值
     * 技术阶段是个单选列表字段，有个选项是其他。如果值是其他，需要取 技术阶段_其他 的值
     */
    public static String setupDySpeciaDeal(String value,String defaltValue){
        if (ProjectConstant._OTHER.equals(value)
                || ProjectConstant._OTHER_ENG.equals(value)
                || ProjectConstant._OTHERS_ENG.equals(value)){
            return defaltValue;
        }
        return value;
    }

    /**
     * string时间转整型
     * @param date
     * @return
     * @throws ParseException
     */
    private static Long stringDate2Int(String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateTime= null;
        try {
            dateTime = format.parse(date);
        } catch (ParseException e) {
            log.info("时间转换失败：【{}】",e);
        }
        long timeLong =dateTime.getTime();
        return timeLong;
    }

    /**
     * 对象降序排列
     */
    public static void sortEntity(List<RetParamEntity> listData){
        Collections.sort(listData, new Comparator<RetParamEntity>() {

            @Override
            public int compare(RetParamEntity Data1, RetParamEntity Data2) {
                if (DataInfoUtil.stringDate2Int(Data2.getYyMmDd()) == DataInfoUtil.stringDate2Int(Data1.getYyMmDd())){
                    if (DataInfoUtil.stringDate2Int(Data2.getSortDate()) < DataInfoUtil.stringDate2Int(Data1.getSortDate())){
                        return -1;
                    }else {
                        return 1;
                    }
                }else if (DataInfoUtil.stringDate2Int(Data2.getYyMmDd()) < DataInfoUtil.stringDate2Int(Data1.getYyMmDd())){
                    return -1;
                }else {
                    return 1;
                }
            }
        });
    }

    public static HashMap<String,String> jsonToHashMap(JSONObject jsonObject){
        HashMap<String, String> hashMap = new HashMap<>();
        if(null != jsonObject){
            try {
                if (StringUtils.isNotBlank(jsonObject.getString("projectProviderName")))
                    hashMap.put("projectProviderName",jsonObject.getString("projectProviderName"));
            }catch (Exception e){
                hashMap.put("projectProviderName", ConfConstant._NULL_STRING);
            }
            try {
                if (StringUtils.isNotBlank(jsonObject.getString("projectName")))
                    hashMap.put("projectName",jsonObject.getString("projectName"));
            }catch (Exception e){
                hashMap.put("projectName",ConfConstant._NULL_STRING);
            }
            try {
                if (StringUtils.isNotBlank(jsonObject.getString("year")))
                    hashMap.put("year",jsonObject.getString("year"));
            }catch (Exception e){
                hashMap.put("year",ConfConstant._NULL_STRING);
            }
        }
        return hashMap;
    }

    /**
     * 时间轴排序
     * @param set
     * @return
     */
    public static List strDatesort(ArrayList<String> set){
        ArrayList<Object> relists = new ArrayList<>();
        Set<String> yearSet = new HashSet<String>();
        for (String yearStr : set){
            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
            //Set<String> stringSet = new HashSet<String>();
            String substring = yearStr.substring(0,4);
            //过滤重复年份
            if (!yearSet.add(substring))continue;
            /*for (String monthStr : set){
                if (substring.equals(monthStr.substring(0,4))){
                    stringSet.add(monthStr.substring(5,7));
                }
            }*/
            //月份排序
            //TreeSet ts = new TreeSet(stringSet);
            //ts.comparator();
            objectObjectHashMap.put("year",substring);
            //objectObjectHashMap.put("month",ts);
            objectObjectHashMap.put("month",new ArrayList<>());
            relists.add(objectObjectHashMap);
        }
        return relists;
    }

    public static boolean strContain(String source,String target){
        if (StringUtils.isBlank(source)
                || StringUtils.isBlank(target))return false;
        if (source.contains(target)){
            return true;
        }
        return false;
    }

    /**
     * 单选列表值
     * @param value
     * @return
     */
    public static String getSingleSelection(String value){
        if (StringUtils.isNotBlank(value)){
            JSONObject jsonObject = JsonUtil.jsonStrToJson(value);
            if (StringUtils.isNotBlank(jsonObject.getString("name"))){
                return jsonObject.getString("name");
            }
        }
        return "";
    }

    /**
     * 主任 Director
     * 财务 Accountant
     * 员工 Staff
     * 这三类工号当作管理员处理
     * @param value
     * @return
     */
    public static Boolean ifManager(String value){
        String typeofPersonnel = DataInfoUtil.getSingleSelection(value);
        if ("主任 Director".equals(typeofPersonnel)
                || "财务 Accountant".equals(typeofPersonnel)
                || "员工 Staff".equals(typeofPersonnel)){
            return true;
        }
        return false;
    }

    /**
     * @company <上海爱湃斯科技有限公司>
     * @email <zhihui.peng@clickpaas.com>
     * @author huiye
     * @decription: 对象复制
     * @date 2021/2/1 2:13 下午
     */
    public static <T> List<T> castListCopy(Object obj, Class<?> clazz, Class<T> reClazz) {
        if (!(obj instanceof List<?>))return null;
        List listObj = (List<?>)obj;
        ArrayList<Future<T>> futures = new ArrayList<>();
        ArrayList<T> returnCodeList = new ArrayList<>();
        ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        try {
            listObj.forEach(source -> {
                Future<T> submit = pool.submit(() -> {
                    try {
                        T t = reClazz.newInstance();
                        BeanUtils.copyProperties(clazz.cast(source), t);
                        return t;
                    } catch (Exception e) {
                        log.info("对象复制报错：【{}】", e);
                        return null;
                    }
                });
                futures.add(submit);
            });
        }catch (Exception e){
            log.info("对象复制线程报错：【{}】",e);
        }finally {
            pool.shutdown();
        }
        futures.forEach(f -> {
            try {
                returnCodeList.add(f.get());
            } catch (Exception e) {
                log.info("对象复制报错：【{}】",e);
            }
        });
        if (returnCodeList.size()>0){
            return returnCodeList;
        }
        return null;
    }
}
